//
//  WLMOAuthViewController.swift
//  WeiBo
//
//  Created by Eric on 2017-01-08.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit
import SVProgressHUD

class WLMOAuthViewController: UIViewController {

    let webView = UIWebView()
    
    //MARK关闭
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func devAccount() {
        let jsString = "document.getElementById('userId').value = '199083626@qq.com',document.getElementById('passwd').value = '121689Eric!@#' "
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    //webView就是根视图
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(titleName: "关闭", target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(titleName: "走后门", target: self, action: #selector(devAccount))
        loadOAuthPage()
    }
    
    //加载微博授权页面
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
}



//在分类中实现某一个协议中需要实现的方法

extension WLMOAuthViewController: UIWebViewDelegate {
    
    
    //实现WebView 的协议方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        //show 指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //dismiss 指示器
        SVProgressHUD.dismiss()
    }
    
    //截取code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url?.absoluteString ?? ""
        let flag = "code="
        if urlString.contains(flag) {
            
            //query 获取url的参数部分
            let query = request.url?.query ?? ""
            print(query)
            let code = (query as NSString).substring(from: flag.characters.count)
            print(code)
            
            //通过code 获取令牌
            //使用账户的视图模型的单利对象来调用获取token的方法
            WLMUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (success) in
                if !success {
                    //如果没有成功
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return
                }
                
                //使用通知来切换根视图控制器
                NotificationCenter.default.post(name: NSNotification.Name.AppChangeRootVC, object: "WLMWelcomeViewController")
                
            })
            
            //在移动应用中不需要加载授权回调页面
            return false
        }
        return true
    }
}






